package com.itheima.health.job;

import com.itheima.health.constant.RedisConstant;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.LocalDateTime;
import java.util.Set;

@Slf4j
public class ClearImgJob implements Job {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("清除图片: " + LocalDateTime.now());
        // 根据Redis中保存的两个Set集合进行差值计算，获得垃圾图片名称

        Set<String> set = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        System.out.println("需要清除的图片 = " + set);

        if (set != null) {
            for (String picName : set) {
                // 删除七牛云服务器器上的图片
                QiniuUtils.deleteFileFromQiniu(picName);

                // 从Redis集合中删除图片名称
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, picName);
            }
        }
    }
}
